<template>
  <div class="container">
    <div class="flex flex-wrap f-ptp10">
      <el-input class='f-mrt20 f-mbt10 f-w120' clearable v-model="id" placeholder="律师ID"></el-input>
      <el-input class='f-mrt20 f-mbt10 f-w120' clearable v-model="mobileNo" placeholder="手机号"></el-input>
      <el-input class='f-mrt20 f-mbt10 f-w120' clearable v-model="name" placeholder="姓名"></el-input>
      <el-date-picker
        class='f-mrt20'
        v-model="date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-button class='f-h40' @click="getList" type="primary">查询</el-button>
      <el-button class='f-h40' @click="exportBtnClickEvent" type="success">导出excel</el-button>
    </div>

    <div>
      <el-table
        :data="lawyerList"
        border
        style="width: 100%">
        <el-table-column prop="id" label="律师ID" width="180"></el-table-column>
        <el-table-column prop="mobileNo" label="手机号" width="180"></el-table-column>
        <el-table-column prop="name" label="姓名" width="180"></el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180">
          <template slot-scope="scope">
            <span>{{tranDate(scope.row.createTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="manage" label="管理">
          <template slot-scope="scope">
            <router-link class='s-c-green f-csp f-mrt10' :to='"/home/lawyer/edit/" + scope.row.id'>编 辑</router-link>
            <span @click="showBillBtnClickEvent(scope.row)" class='s-c-green f-csp f-mrt10'>查看账户</span>
            <router-link class='s-c-green f-csp f-mrt10' :to='"/home/lawyer/detail/" + scope.row.id'>查看详情</router-link>
            <span @click='recommendBtnClickEvent(scope.row)' class='s-c-green f-csp f-mrt10'>{{scope.row.recommend == 0 ? '推荐首页' : '取消推荐'}}</span>
            <!-- <span @click='showDetailBtnClickEvent(scope.row)' class='s-c-green f-csp f-mrt10'>查看详情</span> -->
            <span @click='ProhibitBtnClickEvent(scope.row)' class='f-csp' :class="scope.row.state == 'normal' ? 's-c-red' : 's-c-green'">{{scope.row.state == 'normal' ? '禁 用' : '启 用'}}</span>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="totalCount > 0" class='f-ptp20 f-pbt20'>
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          background
          layout="total, prev, pager, next"
          :total="totalCount">
        </el-pagination>
      </div>
    </div>

    <el-dialog
      title="律师审核"
      :visible.sync="dialogVisible"
      width="560px"
      :before-close="handleClose">
      <div class='d-item'>
        <label for="">律师姓名</label>
        <p>张三</p>
      </div>
      <div class='d-item'>
        <label for="">身份证号</label>
        <p>张三</p>
      </div>
      <div class='d-item'>
        <label for="">性别</label>
        <p>张三</p>
      </div>
      <div class='d-item'>
        <label for="">常用邮箱</label>
        <p>张三</p>
      </div>
      <div class='d-item'>
        <label for="">微信</label>
        <p>张三</p>
      </div>
      <div class='d-item'>
        <label for="">执业证号</label>
        <p>张三</p>
      </div>
      <div class='d-item'>
        <label for="">所在地区</label>
        <p>张三</p>
      </div>
      <div class='d-item'>
        <label for="">擅长专长</label>
        <p>张三</p>
      </div>
      <div class='d-item'>
        <label for="">执业律所</label>
        <p>张三</p>
      </div>
      <div class='d-item'>
        <label for="">详细地址</label>
        <p>张三</p>
      </div>
      <div class='d-item'>
        <label for="">图片信息</label>
        <p>张三</p>
      </div>
      <div class="d-footer">
        <el-button type="primary" @click="dialogVisible = false">通 过</el-button>
        <el-button type="danger" @click="dialogVisible = false">拒 绝</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="查看账户"
      :visible.sync="showBill"
      center
      :before-close="handleBillClose"
      width="660px">
      <div>
        <table class="table" border="1" bordercolor="#ccc"  width="600">
          <!-- <tr>
            <th>余额</th>
            <td width="200">{{billInfo.totalAmount}}</td>
            <td width="150"></td>
          </tr> -->
          <tr>
            <th>冻结资金</th>
            <td>{{billInfo.frozenAmount}}</td>
            <td></td>
          </tr>
          <tr>
            <th>历史余额（只增不减）</th>
            <td>{{billInfo.totalAmountHistory}}</td>
            <td></td>
          </tr>
          <tr>
            <th>可用余额</th>
            <td>
              <span v-if="!isEditBill">{{billInfo.usableAmount}}</span>
              <el-input v-else v-model="usableAmount" />
            </td>
            <td>
              <span class="table_btn" v-if="!isEditBill" @click="isEditBill=true">修改</span>
              <span class="table_btn" v-if="isEditBill" @click="isEditBill=false">取消</span>
              <span class="table_btn" v-if="isEditBill" @click="billSubmit">提交</span>
            </td>
          </tr>
          <tr>
            <th>历史提现金额数量（只增不减）</th>
            <td>{{billInfo.withdrawAmountHistory}}</td>
            <td></td>
          </tr>
        </table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleBillClose">取 消</el-button>
        <el-button type="primary" @click="handleBillClose">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  name: 'LawyerManage',
  data() {
    return {
      isEditBill: false,  // 是否修改账户余额
      bili_userId: null,
      billInfo: {},
      usableAmount: null,
      showBill: false,

      dialogVisible: false,
      id: '',
      mobileNo: '',
      name: '',
      date: '',
      lawyerList: [],
      totalCount: 0,
      pageSize: 10,
      totalPage: 0,
      currentPage: 1,
    }
  },
  created() {
    this.getList();
  },
  methods: {
    // 导出按钮点击事件
    exportBtnClickEvent() {
      if (this.totalCount > 0) {
        this.getAllList();
      }
    },
     // 导出所有数据
    exportAllExcel(list) {
      console.log('list::', list);
      let sheet1 = {
            "!ref": "A1:" + XLSX.utils.encode_cell({c: 3, r: list.length + 1}),
            A1: { v: "律师id", t: "s" },
            B1: { v: "手机号码", t: "s" },
            C1: { v: "姓名", t: "s" },
            D1: { v: "申请时间", t: "s" },
          }
      for(let i = 0; i < list.length; i++) {
        let column_1 = XLSX.utils.encode_cell({c: 0, r: i + 1});
        let column_2 = XLSX.utils.encode_cell({c: 1, r: i + 1});
        let column_3 = XLSX.utils.encode_cell({c: 2, r: i + 1});
        let column_4 = XLSX.utils.encode_cell({c: 3, r: i + 1});
        sheet1[column_1] = {
          v: list[i].id,
          t: "s"
        }
        sheet1[column_2] = {
          v: list[i].mobileNo,
          t: "s"
        }
        sheet1[column_3] = {
          v: list[i].name,
          t: "s"
        }
        sheet1[column_4] = {
          v: list[i].createTime,
          t: "d"
        }

      }
      console.log('sheet1:::', sheet1);
      const workbook = {
        FileName: "export.xlsx",
        SheetNames: ["Sheet1"],
        Sheets: {
          Sheet1: sheet1
        }
      };
      const workbookOut = XLSX.write(workbook, {
        bookType: "xlsx",
        bookSST: false,
        type: "array"
      });
      var date = new Date();
      var fileName = "律师表_" + date.getFullYear() + '_' + (date.getMonth() + 1) + '_' + date.getDate() + ".xlsx";
      try {
        FileSaver.saveAs(
          new Blob([workbookOut], {
            type: "application/octet-stream"
          }),
          fileName
          // "user.xlsx"
        ); //trade-publish.xlsx 为导出的文件名
      } catch (e) {
        console.log(e, workbookOut);
      }
      return workbookOut;
    },
    billSubmit() {
      if(this._utils.isEmpty(this.usableAmount)) {
        this.$message.warning('请输入金额');
        return;
      }
      var usableAmount = this.usableAmount;
      usableAmount = usableAmount.replace(/^00*/, '0');
      console.log('usableAmount::', usableAmount)
      var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
      if (!reg.test(usableAmount)) {
          this.$message.warning('请输入正确金额！');
          return;
      }
      this.updateBill(usableAmount);
    },
    updateBill(usableAmount) {
      this.$store.dispatch('UPDATE_USER_BILL',{
        id: this.billInfo.id,
        usableAmount,
      }).then(res => {
        if(res.data.retCode == 0) {
          console.log('this.res::', res);
          this.getBill();
          this.isEditBill = false;
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      });
    },
    handleBillClose() {
      console.log('befor');
      this.showBill = false;
      this.isEditBill= false;  // 是否修改账户余额
      this.bili_userId= null;
      this.billInfo= {};
      this.usableAmount= null;
    },
    showBillBtnClickEvent(item) {
      console.log('item::', item);
      this.bili_userId = item.userId;
      this.getBill();
      this.showBill = true;

    },
    getBill() {
      this.$store.dispatch('GET_USER_BILL_BY_USER_ID', {
        userId: this.bili_userId
      }).then(res => {
       
        if(res.data.retCode == 0) {
           console.log('res::', res);
           this.billInfo = res.data.data;
           this.usableAmount = res.data.data.usableAmount;
        } else {
          this.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      });
    },
    // 推荐按钮点击事件
    recommendBtnClickEvent(row) {
      console.log('row:::', row);
      const params = {
            userId: row.userId,
            recommend: row.recommend == 0 ? '1' : '0'
        }
        const msg = row.recommend == 0 ? '推荐成功！' : '已取消推荐';
        this.updateLawyer(params, msg);
    },
  
    // 日期转换
    tranDate(date) {
      return this._utils.format(date, 'yyyy-mm-dd');
    },
    // 获取律师列表
    getList() {
      let startDay = '';
      let endDay = '';
      if(this._utils.getType(this.date) == 'Array') {
        startDay = this._utils.format(this.date[0], 'yyyy-mm-dd');
        endDay = this._utils.format(this.date[1], 'yyyy-mm-dd');
      }
      this.$store.dispatch('GET_LAWYER_LIST', {
        pageNum: this.currentPage - 1,
        pageSize: this.pageSize,
        userId: this.id,
        mobileNo: this.mobileNo,
        name: this.name,
        startDay,
        endDay,
      }).then(res => {
        if(res.data.retCode == 0) {
          this.lawyerList = res.data.data;
          this.totalCount = res.data.totalCount;
          this.pageSize = res.data.pageSize;
          this.totalPage = res.data.totalPage
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      
      }).catch(err => {
        console.error('获取律师列表：：', err)
      })
    },
    getAllList() {
      let startDay = '';
      let endDay = '';
      if(this._utils.getType(this.date) == 'Array') {
        startDay = this._utils.format(this.date[0], 'yyyy-mm-dd');
        endDay = this._utils.format(this.date[1], 'yyyy-mm-dd');
      }
      this.$store.dispatch('GET_LAWYER_LIST', {
        pageNum: 0,
        pageSize: this.totalCount,
        userId: this.id,
        mobileNo: this.mobileNo,
        name: this.name,
        startDay,
        endDay,
      }).then(res => {
        if(res.data.retCode == 0) {
          this.exportAllExcel(res.data.data);
        } else {
          this.$message.warning('获取导出数据发生错误！');
        }
      
      }).catch(err => {
        this.$message.warning('获取导出数据发生错误！');
        console.error('获取律师列表：：', err)
      })
    },
    // 查看详情按钮点击事件
    showDetailBtnClickEvent(item) {
      console.log('item:::', item);
      this.dialogVisible = true;
    },
    // 禁用按钮点击事件
    ProhibitBtnClickEvent(row) {
      const msg = row.state == 'normal' ? '禁用' : '启用';
      const msgType = row.state == 'normal' ? 'warning' : 'success';
      this.$confirm('确定要'+ msg + row.name + '该律师？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: msgType
      }).then(() => {
        const msg = row.state == 'normal' ? '已禁用' : '已启用';
        this.updateLawyer({
          userId: row.id,
          state: row.state == 'normal' ? 'frozen' : 'normal'
        }, msg);
      })
    },
    // 更新律师信息
    updateLawyer(params, msg) {
      this.$store.dispatch('UPDATE_LAWYER', params).then(res => {
        if(res.data.retCode == 0) {
          this.getList();
          if(msg) {
            this.$message.success(msg);
          }
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      })
    },
    // 分页组件回调函数
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getList();
    },

    handleClose() {

    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

.d-item{
  overflow: hidden;
}
.d-item>label{
  width: 80px;
  line-height: 32px;
  text-align: right;
  float: left;
}
.d-item>p{
  line-height: 32px;
  float: left;
  padding-left: 20px;
}
.d-footer{
  text-align: center;
  padding-top: 20px;
}
.table th,.table td{
  padding: 8px 5px; 
  font-size: 14px;
}
.table th{
  color: #333;
  font-weight: bold;
}
.table td{
  color: #666;
}
.table_btn{
  display: inline-block;
  border: 1px solid #ccc;
  padding: 0 10px;
  height: 40px;
  border-radius: 4px;
  line-height: 40px;
  margin-left: 10px;
  cursor: pointer;
}
</style>
